package com.think.cloud.thinkshop.auth.config;

import me.zhyd.oauth.cache.AuthStateCache;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

public class RedisStateCache implements AuthStateCache {
    private final RedisTemplate<String, String> redisTemplate;
    private final CacheProperties cacheProperties;

    public void cache(String key, String value) {
        this.cache(key, value, this.cacheProperties.getTimeout().toMillis());
    }

    public void cache(String key, String value, long timeout) {
        this.redisTemplate.opsForValue().set(this.cacheProperties.getPrefix() + key, value, timeout, TimeUnit.MILLISECONDS);
    }

    public String get(String key) {
        return (String) this.redisTemplate.opsForValue().get(this.cacheProperties.getPrefix() + key);
    }

    public boolean containsKey(String key) {
        Long expire = this.redisTemplate.getExpire(this.cacheProperties.getPrefix() + key, TimeUnit.MILLISECONDS);
        if (expire == null) {
            expire = 0L;
        }

        return expire > 0L;
    }

    public RedisStateCache(RedisTemplate<String, String> redisTemplate, CacheProperties cacheProperties) {
        this.redisTemplate = redisTemplate;
        this.cacheProperties = cacheProperties;
    }
}
